package com.itheima.gateway.filter;

import com.google.common.collect.Lists;
import com.itheima.common.token.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author liqp
 * @version 1.0
 * @date 2021/1/28
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final List<String> WHITE_URL = Lists.newArrayList("/user/login", "/user/register");

    private static final String AUTHORIZE_TOKEN = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //判断是否为登陆和注册的请求，如果是，放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        for (String url : WHITE_URL) {
            if (path.contains(url)) {
                //放行
                return chain.filter(exchange);
            }
        }
        //获取请求头的token
        HttpHeaders headers = request.getHeaders();

        String token = headers.getFirst(AUTHORIZE_TOKEN);
        if(StringUtils.isEmpty(token)) {
            //没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析token
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
